package com.foton.logistic.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.foton.logistic.R;
import com.foton.logistic.adapter.SelectAdapter;
import com.foton.logistic.base.BaseActivity;
import com.foton.logistic.listener.IOnItemClickListener;
import com.foton.logistic.listener.IOnRefreshListener;
import com.foton.logistic.listener.IOnResultListener;
import com.foton.logistic.listener.IOnTryClickListener;
import com.foton.logistic.model.CarrierResult;
import com.foton.logistic.model.SelectEntity;
import com.foton.logistic.task.DispatchTask;
import com.foton.logistic.task.ShowLoadTask;
import com.foton.logistic.task.TaskConstant;
import com.foton.logistic.util.BaseConstant;
import com.foton.logistic.util.BroadcastUtil;
import com.foton.logistic.util.net.HttpUtil;
import com.foton.logistic.view.ultimate.UltimateRecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by wuhaocong on 2017/7/5.
 */

public class SelectActivity extends BaseActivity {
    @InjectView(R.id.person_info_user_text)
    EditText personInfoUserText;
    @InjectView(R.id.person_info_number_text)
    EditText personInfoNumberText;
    @InjectView(R.id.select_rec)
    UltimateRecyclerView ultimateRecyclerView;
    @InjectView(R.id.ft_ui_find)
    TextView ftUiFind;
    @InjectView(R.id.select_lin)
    LinearLayout selectLin;
    private LinearLayoutManager linearLayoutManager;
    private SelectAdapter adapter;
    private int pageNumber;
    public List<CarrierResult.DataEntity> list = new ArrayList<>();
    private String name;
    private String number;
    private CarrierResult res;
    private List<CarrierResult.DataEntity> resultList = new ArrayList<>();
    private String carrierId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ft_ui_select);
        ButterKnife.inject(this);
    }

    @Override
    public void init() {
        setBackLayoutVisibility(View.VISIBLE);
        setTitleText("选择承运商");
        setTitleTextVisibility(View.VISIBLE);
        //OptionUtil.openKeyBoard(new Handler(),this,50);
        initUltimate();
        initEdit();
    }

    private void initEdit() {
        personInfoUserText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH){
                    refresh(true);
                    //LogUtil.e("1111111111111");
                    return true;
                }
                return false;
            }
        });
    }

    private void initUltimate() {
        linearLayoutManager = new LinearLayoutManager(this);
        ultimateRecyclerView.setLayoutManager(linearLayoutManager);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        adapter = new SelectAdapter(this, list);
        ultimateRecyclerView.setAdapter(adapter);
        ultimateRecyclerView.enableLoadmore(false);
        ultimateRecyclerView.enableSwipeRefresh(false);
        ultimateRecyclerView.endFinish(false);
        //ultimateRecyclerView.addItemDividerDecoration(this);
        ultimateRecyclerView.setOnRefreshListener(new IOnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh(false);
            }

            @Override
            public void onLoadMore() {
                getRecordList(false);
            }
        });
    }

    void refresh(boolean showLoad) {
        pageNumber = BaseConstant.PAGER_START;
        getRecordList(showLoad);
    }

    IOnTryClickListener iOnTryClickListener = new IOnTryClickListener() {
        @Override
        public void onTry() {
            refresh(true);
        }

        @Override
        public void onOption() {

        }
    };

    void getRecordList(final boolean showLoad) {
        String url = BaseConstant.carrier;
        Map<String, Object> argMap = HttpUtil.getEncryMap(this);
        argMap.put("pageNumber", "" + pageNumber);
        argMap.put("pageSize", "" + BaseConstant.PAGER_COUNT);
        argMap.put("name", name);
        argMap.put("number", number);
        ShowLoadTask task = new ShowLoadTask(this, taskTag, selectLin, loadLayout, "正在加载", showLoad, iOnTryClickListener, url, argMap, TaskConstant.POST);
        task.setParseClass(CarrierResult.class);
        task.setiOnResultListener(new IOnResultListener() {
            @Override
            public void onOK(DispatchTask task) {
                if (task.resultEntity instanceof CarrierResult) {
                    res = (CarrierResult) task.resultEntity;
                    resultList = res.data;
                    updateInfo((ShowLoadTask) task);
                }

               // ftUiFind.setText("请点击选择以下选项");
            }

            @Override
            public void onError(DispatchTask task) {

            }

            @Override
            public void onDone(DispatchTask task) {
                try {
                    ultimateRecyclerView.refreshFinish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        task.execute();
    }

    void updateInfo(ShowLoadTask task) {


        try {

            if (resultList != null) {
                if (pageNumber == BaseConstant.PAGER_START) {
                    list.clear();
                }
                pageNumber++;
                for (CarrierResult.DataEntity dataEntity : resultList) {
                    list.add(dataEntity);
                }
                if (resultList.size() < BaseConstant.PAGER_COUNT) {
                    ultimateRecyclerView.endFinish(true);
                } else {
                    ultimateRecyclerView.endFinish(false);
                }
                if (list.size() == 0 && task != null) {
                    task.addEmptyView("", "", R.mipmap.base_view_link_error);
                }
                adapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        adapter.setIOnItemClickListener(new IOnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                SelectEntity selectEntity = new SelectEntity();
                selectEntity.selectcarrierId = list.get(position).carrierId;
                selectEntity.selectname = list.get(position).name;
                selectEntity.selectnum = list.get(position).number;
                BroadcastUtil.sendSelectBroadcast(SelectActivity.this, selectEntity);
                finishSelf();
            }
        });

    }


    @OnClick(R.id.ft_ui_find)
    public void onViewClicked() {
        name = personInfoUserText.getText().toString().trim();
        number = personInfoNumberText.getText().toString().trim();
        refresh(true);
    }
}
